//
//  XBSudokuView.m
//  BasicModule
//
//  Created by 徐秀滨 on 2018/5/27.
//  Copyright © 2018年 Zoenet (Xiamen) Health Co.,Ltd. All rights reserved.
//

#import "XBSudokuView.h"

@implementation XBSudokuCellView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self){
        _iconImageView = [UIImageView new];
        _titleLabel = [UILabel new];
        _titleLabel.font = [UIFont systemFontOfSize:12];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = rgb(34, 34, 34);
        
        [self addSubview:_iconImageView];
        [self addSubview:_titleLabel];
    }
    return self;
}

@end

@interface XBSudokuView()<UIScrollViewDelegate>

@property (nonatomic, assign) CGFloat cellMarginToCellHorizontal;//水平cell之间的间距，默认0

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSMutableArray *cellViewArray;

@end

@implementation XBSudokuView

- (instancetype)init {
    self = [super init];
    [self afterInitFromSuper];
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    [self afterInitFromSuper];
    return self;
}

- (void)afterInitFromSuper {
    //初始化值
    _cellMarginToSuper = UIEdgeInsetsMake(15, 15, 15, 15);
    _cellMarginToCellHorizontal = 0;
    _cellSize = CGSizeMake(70, 70);
    _columnPerRow = 1;
    _cellMarginToCellHorizontal = 0;
    
    [self setUI];
}

- (void)setUI {
    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    [self addSubview:_scrollView];
}

- (void)reSizeCellMarginHorizontal {
    if(_columnPerRow > 1){
        _cellMarginToCellHorizontal =  (_scrollView.frame.size.width - (_cellMarginToSuper.left + _cellMarginToSuper.right) - _columnPerRow * _cellSize.width) / (_columnPerRow - 1);
    }
}

- (void)refreshFrame {
    [self reSizeCellMarginHorizontal];
    //设置frame
    if(_maxSizePerPage != 0 && _cellCount > self.maxSizePerPage){
        //分页
        NSInteger pageCount = ceil((CGFloat)_cellCount / _maxSizePerPage);
        NSInteger rowCount = ceil((CGFloat)_maxSizePerPage / _columnPerRow);
        CGFloat height = _cellMarginToSuper.top + rowCount * _cellSize.height + (rowCount - 1) * _cellMarginToCellVertical + _cellMarginToSuper.bottom;
        _scrollView.contentSize = CGSizeMake(pageCount * self.frame.size.width, height);
        _scrollView.frame = CGRectMake(0, 0, self.frame.size.width, height);
        CGRect frame = self.frame;
        frame.size.height = _scrollView.frame.size.height;
        self.frame = frame;
    }else{
        //不分页
        NSInteger row = ceil((CGFloat)_cellCount / _columnPerRow);
        CGFloat height = self.cellMarginToSuper.top + row * self.cellSize.height + (row - 1) * self.cellMarginToCellVertical + self.cellMarginToSuper.bottom;
        _scrollView.frame = CGRectMake(0, 0, self.frame.size.width, height);
        _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width, height);
        CGRect frame = self.frame;
        frame.size.height = _scrollView.frame.size.height;
        self.frame = frame;
    }
}

/**
 刷新UI
 */
- (void)refreshUI {
    //frame已经在设置count的时候刷新设置过了，这里不再设置
    //渲染cell
    [self reRenderCell];
    //是否显示分页控件
    if(self.maxSizePerPage != 0 && _cellCount > self.maxSizePerPage){
        self.pageControl.currentPage = 0;
        self.pageControl.numberOfPages = _cellCount / self.maxSizePerPage + 1;
    }
}

/**
 渲染cell
 */
- (void)reRenderCell {
    if(_cellCount == 0){
        return;
    }
    //清空
    [[_scrollView subviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    [self reSizeCellMarginHorizontal];
    
    _cellViewArray = [NSMutableArray new];
    XBSudokuCellView *cellView;
    CGFloat frameX = 0;
    CGFloat frameY = 0;
    NSInteger currentPageIndex = 0;//当前页，1开始
    NSInteger columsPerRow = 1;
    for(NSInteger index = 0; index < _cellCount; index ++){
        //为frame做准备
        if(currentPageIndex == 0 ||
           (_maxSizePerPage > 0 && ceil((CGFloat)(index + 1) / _maxSizePerPage) > currentPageIndex)){
            //新的一页开始
            if(_maxSizePerPage > 0){
                currentPageIndex = ceil((CGFloat)(index + 1) / _maxSizePerPage);
            }else{
                currentPageIndex = 1;
            }
            frameX = _cellMarginToSuper.left + _scrollView.frame.size.width * (currentPageIndex - 1);
            frameY = _cellMarginToSuper.top;
            columsPerRow = 1;
        }else{
            frameX += _cellSize.width + _cellMarginToCellHorizontal;
            if(columsPerRow > _columnPerRow){
                //新的一行
                columsPerRow = 1;
                frameX = _cellMarginToSuper.left + _scrollView.frame.size.width * (currentPageIndex - 1);
                frameY += _cellMarginToCellVertical + _cellSize.height;
            }
        }
        
        //设置frame
        cellView = [self createCellViewWithFrame:CGRectMake(frameX, frameY, _cellSize.width, _cellSize.height) atIndex:index];
        
        //添加
        [_scrollView addSubview:cellView];
        [_cellViewArray addObject:cellView];
        columsPerRow ++;
    }
}


/**
 cell初始化并设置属性

 @param tag tag description
 @return return value description
 */
- (XBSudokuCellView*)createCellViewWithFrame:(CGRect)frame atIndex:(NSInteger)tag {
    XBSudokuCellView *cellView = [[XBSudokuCellView alloc] initWithFrame:frame];
    cellView.tag = tag;
    if(self.titleFont){
        cellView.titleLabel.font = self.titleFont;
    }
    if(self.titleColor){
        cellView.titleLabel.textColor = self.titleColor;
    }
    if(!CGRectEqualToRect(CGRectZero, _imageFrame)){
        cellView.iconImageView.frame = CGRectMake((frame.size.width - _imageFrame.size.width) / 2, _imageFrame.origin.y, _imageFrame.size.width, _imageFrame.size.height);
    }
    if(_titleHeight != 0){
        cellView.titleLabel.frame = CGRectMake(0, frame.size.height - _titleHeight, frame.size.width, _titleHeight);
    }
    if([self.delegate respondsToSelector:@selector(sudokuCell:forIndex:)]){
        [self.delegate sudokuCell:cellView forIndex:tag];
    }
    UITapGestureRecognizer *tap = [UITapGestureRecognizer new];
    [tap.rac_gestureSignal subscribeNext:^(UIGestureRecognizer *tap) {
        [self didSelectCellView:tap.view];
    }];
    [cellView addGestureRecognizer:tap];
    return cellView;
}

- (void)didSelectCellView:(UIView*)cellView {
    if(![cellView isKindOfClass:[XBSudokuCellView class]]){
        return;
    }
    if([self.delegate respondsToSelector:@selector(didSelectItemAtIndex:)]){
        [self.delegate didSelectItemAtIndex:cellView.tag];
    }
}

#pragma mark - Delegate

#pragma mark -UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if(_maxSizePerPage > 0 && _maxSizePerPage < _cellCount){
        NSInteger currentIndex = scrollView.contentOffset.x / scrollView.frame.size.width;
        self.pageControl.currentPage = currentIndex;
    }
}

#pragma mark - 对外

- (void)setCellCount:(NSInteger)cellCount {
    _cellCount = cellCount;
    [self refreshFrame];
}

- (void)reloadData {
    [self refreshUI];
}

#pragma mark - Property

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 13, self.frame.size.width, 13)];
        _pageControl.backgroundColor = [UIColor clearColor];
        _pageControl.currentPageIndicatorTintColor = self.pageCurrentIndicatorColor ? self.pageCurrentIndicatorColor : [UIColor colorWithRed:0/255.0 green:162/255.0 blue:255/255.0 alpha:1];
        _pageControl.pageIndicatorTintColor = self.pageDefaultIndicatorColor ? self.pageDefaultIndicatorColor : [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1];
        [_pageControl setUserInteractionEnabled:NO];
        [self addSubview:_pageControl];
    }
    return _pageControl;
}

@end
